package trading.algo.BullToBearTask;

import java.util.Timer;
import java.util.TimerTask;

import trading.algo.TimerKillerTask;
import trading.algo.BearTask.VIXPricesTaskFinalizeTask;
import trading.bo.DBAccessorBO;
import trading.bo.EmailAccessorBO;
import trading.bo.IBAccessorBO;
import trading.util.Constants;
import trading.util.MarketTimeHelper;
import trading.util.VIXFrontMonthCheckUtil;

public class ProtectionOrderCreationMasterTask extends TimerTask{

	private IBAccessorBO ibAccessorBO;
	private DBAccessorBO dbAccessorBO;
	private EmailAccessorBO emailAccessorBO;
	private MarketTimeHelper marketTimeHelper;
	
	public ProtectionOrderCreationMasterTask(IBAccessorBO ibAccessorBO, DBAccessorBO dbAccessorBO, EmailAccessorBO emailAccessorBO, MarketTimeHelper marketTimeHelper) {
		this.ibAccessorBO = ibAccessorBO;
		this.dbAccessorBO = dbAccessorBO;
		this.emailAccessorBO = emailAccessorBO;
		this.marketTimeHelper = marketTimeHelper;
	}
	
	@Override
	public void run() {
		// Step 1: calculate strike price
		double vixFutureSecondMonth = Double.parseDouble(this.dbAccessorBO.getVIXFutureSecondMonth().get(0));
		this.dbAccessorBO.cleanUpVIXContango();
		double strikePrice = (int)(vixFutureSecondMonth*1.1);
		// Step 2: get expiration month
		String expiration = null;
		// current month is not front month
		if (VIXFrontMonthCheckUtil.getVIXFrontMonthPrice() == null) {
			expiration = this.marketTimeHelper.getNextNextMonthExpiration();
		} else {
			expiration = this.marketTimeHelper.getNextMonthExpiration();
		}
		Timer timer = new Timer();
		int taskID = 0;
		// Step 3: get latest option price
		GetOptionPriceTask getOptionPriceTask = new GetOptionPriceTask(ibAccessorBO, Constants.VIX, expiration, strikePrice, Constants.IB.CALL);
		timer.schedule(getOptionPriceTask, taskID * 1000);
		taskID++;
		
		// Step 4: create protection order
		ProtectionOrderCreationTask protectionOrderCreationTask = new ProtectionOrderCreationTask(dbAccessorBO, ibAccessorBO, emailAccessorBO, expiration, strikePrice);
		timer.schedule(protectionOrderCreationTask, taskID * 1000);
		taskID += 10;
		
        // Step 5: clean up the util
        VIXPricesTaskFinalizeTask finalizeTask = new VIXPricesTaskFinalizeTask();
        timer.schedule(finalizeTask, taskID * 1000);
        taskID += 1;
		
        // Step 6: kill timer
		TimerKillerTask timerKillerTask = new TimerKillerTask(timer);
		timer.schedule(timerKillerTask, taskID * 1000);
	}
}
